<?php

namespace app\api\model;

class OauthIntegral extends \app\common\model\OauthIntegral
{
    /**
     * 积分变化列表 | 签到列表
     * @param $oauthId
     * @param $integral
     * @param int $type 积分获取类型
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($oauthId, $integral, $type, $page, $size)
    {
        $offset = ($page - 1) * $size;

        $sql = static::where(['oauth_id' => $oauthId]);

        // 存在type，则获取指定类型的积分列表
        if ($type > 0) {
            $sql->where(['type' => $type]);
        }

        $date = date('Y-m-d');
        // 签到列表获取所有签到记录，积分变化列表获取当天的
        if ($type != self::TYPE_SIGN) {
            $sql = $sql->where('create_time', '>=', strtotime($date));
        }

        $model = $sql->field('id, type, (after_num - before_num) AS integral, 
        order_id AS orderId, create_time AS createTime')
            ->order(['create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();

        $orderIds = [];
        foreach ($model as $key => $value) {
            $orderIds[$value['orderId']] = $value['orderId'];
            $model[$key]['type'] = self::attributes('type', $value['type']);
            $model[$key]['createTime'] = date('Y-m-d H:i:s', $value['createTime']);
        }

        $class = [];
        if ($orderIds) {
            $class = OauthOrderClass::getClassByOrder($orderIds);
        }

        foreach ($model as $key => $value) {
            $model[$key]['className'] = isset($class[$value['orderId']]) ? implode(',', $class[$value['orderId']]) : '';
        }

        $sum = static::where(['oauth_id' => $oauthId])
            ->field('SUM(after_num - before_num) AS integral')
            ->where('type', '<>', self::TYPE_BUY)
            ->select()
            ->column('integral');

        return [
            'date' => $date,
            'sum' => isset($sum[0]) ? $sum[0] : 0,
            'rest' => $integral,
            'list' => $model,
            'count' => $sql->count()
        ];
    }

    /**
     * 查找指定用户指定类型当天一条记录
     * @param $oauthId
     * @param $type
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public static function getOne($oauthId, $type)
    {
        $time = strtotime(date('Y-m-d'));
        return static::field('id')
            ->where(['oauth_id' => $oauthId, 'type' => $type])
            ->where('create_time', '>=', $time)
            ->find();
    }
}